import { ValidationPipe } from "@nestjs/common";
import { HttpAdapterHost, NestFactory, Reflector } from "@nestjs/core";
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
import * as packageJson from "../package.json";
import { AppModule } from "./app.module";
import { HttpExceptionFilter } from "./filters/http-exception.filter";
import { RolesGuard } from "./guards/roles.guard";
import { LoggingInterceptor } from "./interceptors/logging.interceptor";
import { NormalizationInterceptor } from "./interceptors/normalization.interceptor";

async function bootstrap() {
	const app = await NestFactory.create(AppModule);

	const adapterHost = app.get(HttpAdapterHost);
	const reflector = app.get(Reflector);

	app.useGlobalFilters(new HttpExceptionFilter(adapterHost));
	app.useGlobalInterceptors(
		new LoggingInterceptor(adapterHost),
		new NormalizationInterceptor(reflector, adapterHost),
	);
	app.useGlobalPipes(
		new ValidationPipe({
			transform: true,
			transformOptions: {
				enableImplicitConversion: true,
			},
			validationError: {
				target: true,
				value: true,
			},
		}),
	);

	app.useGlobalGuards(new RolesGuard(reflector));

	const config = new DocumentBuilder()
		.setTitle(packageJson.name)
		.setDescription(packageJson.description)
		.setVersion(packageJson.version)
		.build();
	const document = SwaggerModule.createDocument(app, config);
	SwaggerModule.setup("swagger", app, document);

	await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
